package com.tbit.main.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.main.constant.AccountConfigExtConstant;
import com.tbit.main.constant.GatewayProtocol;
import com.tbit.main.constant.MachineAbnormalConstant;
import com.tbit.main.constant.RedisConstant;
import com.tbit.main.constant.enums.MachineAlarmEnum;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

import static com.tbit.main.constant.ReportConstant.*;
import static com.tbit.main.util.TimeUtil.dateDiff;

@Slf4j
@Service("managerListenter")
public class ManagerListenter {
    @Autowired
    private RedisService redisService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MachineAlarmService machineAlarmService;
    @Autowired
    private DataService dataService;
    @Autowired
    private MachineAbnormalService machineAbnormalService;
    @Autowired
    private HelmetService helmetService;
    @Autowired
    private HelmetAbnormalService helmetAbnormalService;
    @Autowired
    private HelmetBoundService helmetBoundService;
    @Autowired
    private SmsSendAlarmService smsSendAlarmService;

    @RabbitListener(queues = {"${mq.queue.tbitUqbikeWebManagerTestOnline}"}, concurrency = "5")
    @RabbitHandler
    public void onMessage(Message msg) {
        try {
            String respMsg = new String(msg.getBody(), StandardCharsets.UTF_8);
            /* 判断消息类型 */
            JSONObject object = JSON.parseObject(respMsg);
            int msgId = object.getIntValue("msgId");

            if (msgId == GatewayProtocol.MQ_MSG_ID_ALARM_PUSH) {

                log.info("车辆告警：{}", object.getString("data"));
                /* 告警 */
                Alarm alarm = JSONObject.parseObject(object.getString("data"), Alarm.class);
                if (dataService.getMachineIdLister(alarm.getMachineNO()) != null) {
                    Machine machine = dataService.getMachine(dataService.getMachineId(alarm.getMachineNO()));

                    if (machine != null) {
                        MachineAlarmEnum machineAlarmEnum = null;

                        String timeNew = DateTimeUtil.getNowTime();

                        // 运营区域
                        Integer accountId = machine.getAccountId();
                        Account account = accountService.getByAccountId(accountId);
                        // 区域资产预警配置
                        MachineAlarm machineAlarm = machineAlarmService.getByAccountId(accountId);

                        if (alarm.getAlarmType().equals(LDBJ) || alarm.getAlarmType().equals(ZDGJ)) {

                            if (machineAlarm != null && machineAlarm.getIllegalityMoveSwitch() == 1) {
                                // 获取redis数据
                                String timeRedis = redisService.get(RedisConstant.REDIS_KEY_ILLEGALITY_MOVE + alarm.getMachineNO());
                                if (timeRedis == null) {
                                    redisService.add(RedisConstant.REDIS_KEY_ILLEGALITY_MOVE + alarm.getMachineNO(), timeNew, 60 * 10);
                                } else {
                                    Integer distance = historyService.getMileageByMachineNOAndTime(alarm.getMachineNO(), DateTimeUtil.getTimeNestMin(timeNew, 10), timeNew);
                                    long time = dateDiff(machine.getLastBorrowTime(), timeNew, "yyyy-MM-dd HH:mm:ss");
                                    log.info("非法移动：车辆：{},距离：{},时间：{}", machine.getUserCode(), distance, time);
                                    if (time > 10 && distance != null && distance > 100) {

                                        /* 判断是否第二次 */
                                        String machineNoSms = redisService.get(RedisConstant.REDIS_KEY_ILLEGALITY_MOVE + ".SMS" + alarm.getMachineNO());
                                        if (machineNoSms == null) {
                                            machineAlarmEnum = MachineAlarmEnum.MACHINE_ALARM_ILLEGALITY_MOVE;
                                            redisService.add(RedisConstant.REDIS_KEY_ILLEGALITY_MOVE + ".SMS" + alarm.getMachineNO(), timeNew, 60 * 10);
                                        }
                                    }
                                }
                            }
                        } else if (alarm.getAlarmType().equals(CFGJ)) {
                            if (machineAlarm != null && machineAlarm.getRolloverSwitch() == 1) {

                                // 获取redis数据
                                String timeRedis = redisService.get(RedisConstant.REDIS_KEY_ILLEGALITY_ROLL + alarm.getMachineNO());
                                if (timeRedis == null) {
                                    machineAlarmEnum = MachineAlarmEnum.MACHINE_ALARM_ROLLOVER;
                                    redisService.add(RedisConstant.REDIS_KEY_ILLEGALITY_ROLL + alarm.getMachineNO(), timeNew, 60 * 4);
                                }
                            }
                        } else if (alarm.getAlarmType().equals(SXTGZ)) {
                            if (machineAlarm != null && machineAlarm.getCameraSwitch() == 1) {
                                // 获取redis数据
                                String timeRedis = redisService.get(RedisConstant.REDIS_KEY_ILLEGALITY_SXTGZ + alarm.getMachineNO());
                                if (timeRedis == null) {
                                    machineAlarmEnum = MachineAlarmEnum.MACHINE_ALARM_CAMERA;
                                    redisService.add(RedisConstant.REDIS_KEY_ILLEGALITY_SXTGZ + alarm.getMachineNO(), timeNew, 60 * 60 * 6);
                                }
                            }
                        } else if (alarm.getAlarmType().equals(SXTZD)) {
                            if (machineAlarm != null && machineAlarm.getCameraCoverSwitch() == 1) {
                                // 获取redis数据
                                String timeRedis = redisService.get(RedisConstant.REDIS_KEY_ILLEGALITY_SXTZD + alarm.getMachineNO());
                                if (timeRedis == null) {
                                    machineAlarmEnum = MachineAlarmEnum.MACHINE_ALARM_CAMERA_COVER;
                                    redisService.add(RedisConstant.REDIS_KEY_ILLEGALITY_SXTZD + alarm.getMachineNO(), timeNew, 60 * 60 * 6);
                                }
                            }
                        } else if (alarm.getAlarmType().equals(TKSTX) || alarm.getAlarmType().equals(TKSDD) || alarm.getAlarmType().equals(HLSGZ)) {
                            AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.helmetAbnormal);
                            if (accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
                                MachineAbnormal machineAbnormal = machineAbnormalService.getByMachineIdAndType(machine.getMachineId(), MachineAbnormalConstant.MACHINE_ABNORMAL__HELMET);
                                if (machineAbnormal == null) {
                                    machineAbnormalService.insert(new MachineAbnormal(accountId, machine.getMachineId(), machine.getUserCode(), machine.getMachineNO()
                                            , MachineAbnormalConstant.MACHINE_ABNORMAL__HELMET, timeNew, null, 0));
                                }
                                int type = 0;
                                if (alarm.getAlarmType().equals(TKSTX)) {
                                    type = 1;
                                } else if (alarm.getAlarmType().equals(TKSDD)) {
                                    type = 2;
                                } else if (alarm.getAlarmType().equals(HLSGZ)) {
                                    type = 3;
                                }
                                Helmet helmet = helmetBoundService.getMachineId(machine.getMachineId());
                                if (helmet != null) {
                                    HelmetAbnormal helmetAbnormal = helmetAbnormalService.getMachineIdType(machine.getMachineId(), type);
                                    if (helmetAbnormal == null) {
                                        log.info("添加头盔锁异常(machineId: {})", machine.getMachineId());
                                        helmetAbnormalService.insert(new HelmetAbnormal(null, machine.getMachineId(), null, null, type, timeNew, null, null));
                                        helmetService.updateState(helmet.getHelmetMac(), 1);
                                    }
                                }
                            }
                        }
                        if (machineAlarmEnum != null) {
                            smsSendAlarmService.sendSmsAlarm(account.getName(), machine, machineAlarmEnum);
                        }

                    }
                }
            } else {
                log.warn("未知消息类型={}", msgId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
